package com.xuan.yupao.controller;


import com.xuan.yupao.common.ErrorCode;
import com.xuan.yupao.common.Result;
import com.xuan.yupao.exception.BusinessException;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.model.domain.vo.UserVo;
import com.xuan.yupao.service.FollowService;
import com.xuan.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/follow")
public class FollowController {

    @Resource
    private FollowService followService;

    @Resource
    private UserService userService;

    @PostMapping("/{userId}")
    public Result<String> followOrUnfollowUser(@PathVariable(value = "userId") Long userId, HttpServletRequest request) {
        if (userId == null || userId < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数非法");
        }
        // 先查看用户是否登录以及所关注的用户是否存在
        User loginUser = userService.getLoginUser(request);
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        log.info("userId=" + userId + ", fan_id=" + loginUser.getId());

        String result = followService.followOrUnfollowUser(userId, loginUser.getId());
        return Result.success(result);
    }


    @GetMapping("/my")
    public Result<List<UserVo>> getFollowUsers(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<UserVo> userVoList = followService.getFollowUsers(loginUser.getId());
        return Result.success(userVoList);
    }


    @GetMapping("/fans")
    public Result<List<UserVo>> getMyFans(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<UserVo> userVoList = followService.getMyFans(loginUser.getId());
        return Result.success(userVoList);
    }
}
